package com.atao.baokede.chatMemory;

import com.atao.baokede.mapper.AiDialogueMapper;
import com.atao.baokede.pojo.AiDialogue;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class MysqlChatMemory implements ChatMemory {
    
    @Autowired
    private AiDialogueMapper aiDialogueMapper;
    
    @Override
    public void add(String conversationId, Message message) {
        // 这个方法现在不直接处理消息配对
        // 配对逻辑移动到AiController中
    }
    
    /**
     * 直接保存完整的对话记录
     */
    public void saveDialogue(String conversationId, String userMessage, String aiMessage) {
        Long userId = Long.valueOf(conversationId);
        AiDialogue dialogue = new AiDialogue();
        dialogue.setUserId(userId);
        dialogue.setUserMessage(userMessage);
        dialogue.setAiMessage(aiMessage);
        
        aiDialogueMapper.insertDialogue(dialogue);
        System.out.println("Saved dialogue for user: " + userId + ", user msg length: " + userMessage.length() + ", ai msg length: " + aiMessage.length());
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        for (Message message : messages) {
            add(conversationId, message);
        }
    }

    @Override
    public List<Message> get(String conversationId) {
        Long userId = Long.valueOf(conversationId);
        List<AiDialogue> dialogues = aiDialogueMapper.getRecentDialogues(userId,5);

        List<Message> messages = new ArrayList<>();
        // 需要反转顺序，因为数据库查询是按时间倒序的
        Collections.reverse(dialogues);

        for (AiDialogue dialogue : dialogues) {
            // 添加用户消息
            messages.add(new UserMessage(dialogue.getUserMessage()));
            // 添加AI回复
            messages.add(new AssistantMessage(dialogue.getAiMessage()));
        }

        return messages;
    }


    @Override
    public void clear(String conversationId) {
        Long userId = Long.valueOf(conversationId);
        aiDialogueMapper.clearDialogues(userId);
    }
}
